package org.eenie.kdassistant.ui.login.xz;

import android.app.Activity;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.yunda.crypt.NativeEncryption;

import org.eenie.kdassistant.R;
import org.eenie.kdassistant.net.ParamsAnalog;
import org.eenie.kdassistant.net.kdy_api.KdyApi;
import org.eenie.kdassistant.net.xz_api.XingZheApi;
import org.eenie.kdassistant.net.xz_api.request.AuthImageResp;
import org.eenie.kdassistant.net.yd_api.YDApi;
import org.eenie.kdassistant.net.yd_api.YDBaseResponse;
import org.eenie.kdassistant.net.yd_api.entity.LoginRes;
import org.eenie.kdassistant.net.yd_api.entity.UserEntityDao;
import org.eenie.kdassistant.net.yd_api.entity.UserRes;
import org.eenie.kdassistant.net.zzt_api.ZZTApi;
import org.eenie.kdassistant.ui.BaseActivity;
import org.eenie.kdassistant.utils.ToastUtils;

import java.io.IOException;

import okhttp3.ResponseBody;
import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

public class XingZheLoginActivity extends BaseActivity {

    Button btnLogin;
    KdyApi mKdyApi;
    ZZTApi mZZTApi;
    XingZheApi mXingZheApi;
    YDApi mYDApi;


    int src = 0;

    String title;


    EditText edit_username;
    EditText edit_sms_code;
    EditText edit_pic_code;
    EditText edit_pwd;

    ParamsAnalog mParamsAnalog;


    LinearLayout ll_sms_code;
    LinearLayout ll_pic_code;
    ImageView img_code;

    Button btn_send;

    UserEntityDao userEntityDao;


    @Override
    public int initContentView() {
        return R.layout.activity_xing_zhe_login;
    }

    @Override
    public void initInjector() {
        mXingZheApi = getApplicationComponent().getXzApi();
        mKdyApi = getApplicationComponent().getKdyApi();
        mZZTApi = getApplicationComponent().getZZTApi();
        mYDApi = getApplicationComponent().getYDApi();
        src = getIntent().getIntExtra("src", 0);

        userEntityDao = getApplicationComponent().getDaoSession().getUserEntityDao();
        mParamsAnalog = getApplicationComponent().getParamsAnalog();

        switch (src) {
            case 0:
                title = "行者登录";
                break;
            case 1:
                title = "快递员登录";
                break;
            case 2:
                title = "韵达登录";
                break;
        }
    }

    @Override
    public void initUiAndListener() {
        setTitle(title);
        edit_username = (EditText) findViewById(R.id.edit_username);
        edit_pwd = (EditText) findViewById(R.id.edit_pwd);
        edit_pic_code = (EditText) findViewById(R.id.edit_pic_code);
        edit_sms_code = (EditText) findViewById(R.id.edit_sms_code);
        img_code = (ImageView) findViewById(R.id.img_code);
        btn_send = (Button) findViewById(R.id.btn_send);
        btn_send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ll_pic_code.getVisibility() == View.VISIBLE && TextUtils.isEmpty(edit_pic_code.getText().toString())) {
                    ToastUtils.showShort("请输入图片验证码");
                    return;
                }

                switch (src) {
                    case 0:
                        XzSendSms(edit_username.getText().toString());
                        break;
                    case 2:
                        mYDApi.fetchSmsCode(edit_username.getText().toString(), edit_pic_code.getText().toString())
                                .subscribeOn(Schedulers.io())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Observer<YDBaseResponse>() {
                                    @Override
                                    public void onCompleted() {

                                    }

                                    @Override
                                    public void onError(Throwable e) {
                                        e.printStackTrace();
                                    }

                                    @Override
                                    public void onNext(YDBaseResponse baseResponse) {
                                        ToastUtils.showShort("短信发送成功");
                                    }
                                });
                        break;
                }


            }
        });

        ll_sms_code = (LinearLayout) findViewById(R.id.ll_sms_code);
        ll_pic_code = (LinearLayout) findViewById(R.id.ll_pic_code);

        btnLogin = (Button) findViewById(R.id.btn_login);
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (src) {
                    case 0:
                        String picCode = ll_pic_code.getVisibility() == View.VISIBLE ? edit_pic_code.getText().toString() : "";
                        String smsCode = ll_sms_code.getVisibility() == View.VISIBLE ? edit_sms_code.getText().toString() : "";
                        XzLogin(edit_username.getText().toString(), edit_pwd.getText().toString(), picCode, smsCode);
                        break;
                    case 1:
                        kdyLogin(edit_username.getText().toString(), edit_pwd.getText().toString());
                        break;
                    case 2:
                        if (ll_sms_code.getVisibility() == View.VISIBLE) {
                            YDBindDevice(edit_username.getText().toString(), edit_sms_code.getText().toString())
                                    .subscribe(new Observer<YDBaseResponse>() {
                                        @Override
                                        public void onCompleted() {

                                        }

                                        @Override
                                        public void onError(Throwable e) {
                                            e.printStackTrace();
                                        }

                                        @Override
                                        public void onNext(YDBaseResponse baseResponse) {
                                            if (baseResponse.getSuccess()) {
                                                YDLogin();
                                            } else {
                                                ToastUtils.showShort(baseResponse.getErrorcode());
                                            }


                                        }
                                    });
                        } else {
                            YDLogin();
                        }
                        break;
                }
            }
        });

    }

    private void XzLogin(final String account, String pwd, String picCode, String smsCode) {
        mXingZheApi.login(account, pwd, picCode, smsCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<JSONObject>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(JSONObject resObj) {
                        if (resObj.getInteger("code") == 1000) {
                            JSONObject dataObj = resObj.getJSONObject("obj");
                            mParamsAnalog.setXz_uuid(dataObj.getString("uuid"));
                            setResult(Activity.RESULT_OK);
                            finish();
                        } else if (resObj.getInteger("code") == 2025 || resObj.getInteger("code") == 2006 || resObj.getInteger("code") == 1112) {
                            JSONObject dataObj = resObj.getJSONObject("obj");
                            if (dataObj.getBoolean("needImageAuthCode")) {
                                ll_pic_code.setVisibility(View.VISIBLE);
                                XzGetPicCode(account);
                            }

                            if (dataObj.getBoolean("needPhoneCode")) {
                                ll_sms_code.setVisibility(View.VISIBLE);
                            }
                            String msg = resObj.getString("prompt");
                            ToastUtils.showShort(msg);

                        } else {
                            String msg = resObj.getString("prompt");
                            ToastUtils.showShort(msg);
                        }
                    }
                });
    }


    private void kdyLogin(String string, String s) {
        mKdyApi.login(string, s)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            JSONObject resObj = JSON.parseObject(responseBody.string());
                            if (resObj.getInteger("code") == 0) {
                                String ssid = resObj.getJSONObject("data").getString("session_id");
                                mParamsAnalog.setKdy_sessionId(ssid);
                                setResult(Activity.RESULT_OK);
                                finish();
                            } else {
                                String msg = resObj.getString("msg");
                                ToastUtils.showShort(msg);
                            }

                        } catch (IOException e) {
                            e.printStackTrace();
                        }


                    }
                });
    }


    private void XzSendSms(String account) {
        mXingZheApi.sendSms(account)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(ResponseBody response) {
                        try {
                            JSONObject resObj = JSON.parseObject(response.string());
                            if (resObj.getInteger("code") == 1000) {
                                String msg = resObj.getJSONObject("extMap").getString("commonParam");
                                ToastUtils.showShort(msg);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }


    private void XzGetPicCode(String account) {
        mXingZheApi.getPicCode(account)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(ResponseBody response) {
                        try {
                            JSONObject resObj = JSON.parseObject(response.string());
                            if (resObj.getInteger("code") == 1000) {
                                AuthImageResp resp = resObj.getObject("obj", AuthImageResp.class);
                                img_code.setImageBitmap(BitmapFactory.decodeByteArray(resp.getImageBytes(), 0, resp.getImageBytes().length));

                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    public void YDLogin() {
        mYDApi.login(edit_username.getText().toString(), edit_pwd.getText().toString())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<YDBaseResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(YDBaseResponse responseBody) {
                        LoginRes loginRes = (LoginRes) responseBody.getEntity(LoginRes.class);
                        String publicKey = loginRes.getPublicKey();
                        String token = loginRes.getToken();
                        mParamsAnalog.setYd_token(token);
                        mParamsAnalog.setYd_public_key(publicKey);
                        mParamsAnalog.setYDUserInfo(JSON.toJSONString(loginRes.getUserinfo()));
                        userEntityDao.deleteAll();
                        NativeEncryption.JNI_EDCodeInstance("bapp.yundasys.com", 2059, mParamsAnalog.getYd_token(), "5.6.0", mParamsAnalog.getYd_public_key());
                        if (loginRes.getUserinfo().getDevst().equals("0")) {
                            fetchUser();
                        } else {

                            fetchYDPicCode(edit_username.getText().toString());
                        }


                    }
                });
    }


    private void fetchUser() {
        mYDApi.getUserList().subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<YDBaseResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(YDBaseResponse baseResponse) {

                        UserRes userRes = (UserRes) baseResponse.getDeEntity(UserRes.class);
                        if (!userRes.getList().isEmpty()) {
                            userRes.getList().get(0).setChecked(true);
                        }

                        userEntityDao.deleteAll();
                        userEntityDao.insertInTx(userRes.getList());


                        finish();
                    }
                });
    }

    private void fetchYDPicCode(String mobile) {
        mYDApi.fetchPicCode(mobile)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<YDBaseResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(YDBaseResponse baseResponse) {

                        if (baseResponse.getSuccess()) {
                            ll_pic_code.setVisibility(View.VISIBLE);
                            ll_sms_code.setVisibility(View.VISIBLE);
                            ToastUtils.showShort("请输入短信验证码");

                            String url = baseResponse.getEntity().getJSONObject("res").getString("picUrl");

                            RequestOptions options = new RequestOptions();
                            options.diskCacheStrategy(DiskCacheStrategy.NONE)
                                    .skipMemoryCache(true);


                            Glide.with(mContext).load(url)
                                    .apply(options)
                                    .into(img_code);


                        }


                    }
                });
    }


    private Observable<YDBaseResponse> YDBindDevice(String mobile, String smsCode) {
        return mYDApi.bindDevice(mobile, smsCode)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread());
    }


    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return false;
    }
}
